<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
 */
class video_api{
	
	public function parse($url='', $createObject=false){
		$lowerurl = strtolower($url);
		preg_match("/(youku\.com|redtube\.com|tudou\.com|ku6\.com|56\.com|letv\.com|video\.sina\.com\.cn|(my\.)?tv\.sohu\.com|v\.qq\.com|youtube\.com|iqiyi\.com)/", $lowerurl, $matches);
		if(!$matches) return false;

		switch($matches[1]){
			case 'youku.com':
				$data = $this->_parseYouku($url);
				break;
			case 'redtube.com':
				$data = $this->_parseRedtube($url);
				break;
			case 'tudou.com':
				$data = $this->_parseTudou($url);
				break;
			case 'ku6.com':
				$data = $this->_parseKu6($url);
				break;
			case '56.com':
				$data = $this->_parse56($url);
				break;
			case 'letv.com':
				$data = $this->_parseLetv($url);
				break;
			case 'video.sina.com.cn':
				$data = $this->_parseSina($url);
				break;
			case 'my.tv.sohu.com':
			case 'tv.sohu.com':
			case 'sohu.com':
				$data = $this->_parseSohu($url);
				break;
			case 'v.qq.com':
				$data = $this->_parseQq($url);
				break;
			case 'youtube.com':
				$data = $this->_parseYoutube($url);
				break;
			case 'iqiyi.com':
				$data = $this->_parseiqi($url);
				break;
			default:
				$data = false;
		}

		if($data && $createObject) $data['object'] = "<embed src=\"{$data['flv']}\" quality=\"high\" width=\"480\" height=\"400\" align=\"middle\" allowNetworking=\"all\" allowScriptAccess=\"always\" type=\"application/x-shockwave-flash\"></embed>";
		return $data;
	}
	/**
	 * 腾讯视频
	 * http://v.qq.com/cover/o/o9tab7nuu0q3esh.html?vid=97abu74o4w3_0
	 * http://v.qq.com/play/97abu74o4w3.html
	 * http://v.qq.com/cover/d/dtdqyd8g7xvoj0o.html
	 * http://v.qq.com/cover/d/dtdqyd8g7xvoj0o/9SfqULsrtSb.html
	 * http://imgcache.qq.com/tencentvideo_v1/player/TencentPlayer.swf?_v=20110829&vid=97abu74o4w3&autoplay=1&list=2&showcfg=1&tpid=23&title=%E7%AC%AC%E4%B8%80%E7%8E%B0%E5%9C%BA&adplay=1&cid=o9tab7nuu0q3esh
	 */
	private function _parseQq($url){
		if(preg_match("/\/play\//", $url)){
			$html = get_contents($url);
			preg_match("/url=[^\"]+/", $html, $matches);
			if(!$matches); return false;
			$url = $matches[0];
		}
		preg_match("/vid=([^\_]+)/", $url, $matches);
		$vid = $matches[1];
		$html = get_contents($url);
		// query
		preg_match("/flashvars\s=\s\"([^;]+)/s", $html, $matches);
		$query = $matches[1];
		if(!$vid){
			preg_match("/vid\s?=\s?vid\s?\|\|\s?\"(\w+)\";/i", $html, $matches);
			$vid = $matches[1];
		}
		$query = str_replace('"+vid+"', $vid, $query);
		parse_str($query, $output);
		$data['imgurl'] = "http://vpic.video.qq.com/{$$output['cid']}/{$vid}_1.jpg";
		$data['url'] = $url;
		$data['title'] = $output['title'];
		$data['flv'] = "http://imgcache.qq.com/tencentvideo_v1/player/TencentPlayer.swf?".$query;
		return $data;
	}


	/**
	 * 优酷网
	 * http://v.youku.com/v_show/id_XMjI4MDM4NDc2.html
	 * http://player.youku.com/player.php/sid/XMjU0NjI2Njg4/v.swf
	 */
	private function _parseYouku($url){
		preg_match("#id\_(\w+)#", $url, $matches);

		if (empty($matches)){
			preg_match("#v_playlist\/#", $url, $mat);
			if(!$mat) return false;

			$html = get_contents($url);

			preg_match("#videoId2\s*=\s*\'(\w+)\'#", $html, $matches);
			if(!$matches) return false;
		}

		$link = "http://v.youku.com/player/getPlayList/VideoIDS/{$matches[1]}/timezone/+08/version/5/source/out?password=&ran=2513&n=3";

		$retval = get_contents($link);
		if ($retval) {
			$json = json_decode($retval, true);

			$data['imgurl'] = $json['data'][0]['logo'];
			$data['title'] = $json['data'][0]['title'];
			$data['url'] = $url;
			$data['flv'] = "http://player.youku.com/player.php/sid/{$matches[1]}/v.swf";

			return $data;
		} else {
			return false;
		}
	}

	/**
	 * 土豆网
	 * http://www.tudou.com/programs/view/Wtt3FjiDxEE/
	 * http://www.tudou.com/v/Wtt3FjiDxEE/v.swf
	 *
	 * http://www.tudou.com/playlist/p/a65718.html?iid=74909603
	 * http://www.tudou.com/l/G5BzgI4lAb8/&iid=74909603/v.swf
	 */
	private function _parseTudou($url){
		preg_match("#view/([-\w]+)/#", $url, $matches);

		if (empty($matches)) {
			if (strpos($url, "/playlist/") == false) return false;

			if(strpos($url, 'iid=') !== false){
				$quarr = explode("iid=", $lowerurl);
				if (empty($quarr[1]))  return false;
			}elseif(preg_match("#p\/l(\d+).#", $lowerurl, $quarr)){
				if (empty($quarr[1])) return false;
			}

			$html = get_contents($url);
			$html = iconv("GB2312", "UTF-8", $html);

			preg_match("/lid_code\s=\slcode\s=\s[\'\"]([^\'\"]+)/s", $html, $matches);
			$icode = $matches[1];

			preg_match("/iid\s=\s.*?\|\|\s(\d+)/sx", $html, $matches);
			$iid = $matches[1];

			preg_match("/listData\s=\s(\[\{.*\}\])/sx", $html, $matches);

			$find = array("/\n/", '/\s/', "/:[^\d\"]\w+[^\,]*,/i", "/(\{|,)(\w+):/");
			$replace = array("", "", ':"",', '\\1"\\2":');
			$str = preg_replace($find, $replace, $matches[1]);
			$json = json_decode($str);
			if(is_array($json) || is_object($json) && !empty($json)){
				foreach ($json as $val) {
					if ($val->iid == $iid) {
						break;
					}
				}
			}

			$data['imgurl'] = $val->pic;
			$data['title'] = $val->title;
			$data['url'] = $url;
			$data['flv'] = "http://www.tudou.com/l/{$icode}/&iid={$iid}/v.swf";

			return $data;
		}

		$host = "www.tudou.com";
		$path = "/v/{$matches[1]}/v.swf";

		$ret = pfsget($path, $host);

		if (preg_match("#\nLocation: (.*)\n#", $ret, $mat)) {
			parse_str(parse_url(urldecode($mat[1]), PHP_URL_QUERY));

			$data['imgurl'] = $snap_pic;
			$data['title'] = $title;
			$data['url'] = $url;
			$data['flv'] = "http://www.tudou.com/v/{$matches[1]}/v.swf";

			return $data;
		}
		return false;
	}

	/**
	 * 酷6网
	 * http://v.ku6.com/film/show_520/3X93vo4tIS7uotHg.html
	 * http://v.ku6.com/special/show_4926690/Klze2mhMeSK6g05X.html
	 * http://v.ku6.com/show/7US-kDXjyKyIInDevhpwHg...html
	 * http://player.ku6.com/refer/3X93vo4tIS7uotHg/v.swf
	 */
	private function _parseKu6($url){
		if(preg_match("/show\_/", $url)){
			preg_match("#/([^\/]+)\.html#", $url, $matches);
			$url = "http://v.ku6.com/fetchVideo4Player/{$matches[1]}.html";
			$html = get_contents($url);

			if ($html) {
				$json = json_decode($html, true);
				if(!$json) return false;

				$data['imgurl'] = $json['data']['picpath'];
				$data['title'] = $json['data']['t'];
				$data['url'] = $url;
				$data['flv'] = "http://player.ku6.com/refer/{$matches[1]}/v.swf";

				return $data;
			} else {
				return false;
			}
		}elseif(preg_match("/show\//", $url, $matches)){
			$html = get_contents($url);
			preg_match("/ObjectInfo\s?=\s?([^\n]*)};/si", $html, $matches);
			$str = $matches[1];
			// img
			preg_match("/cover\s?:\s?\"([^\"]+)\"/", $str, $matches);
			$data['imgurl'] = $matches[1];
			// title
			preg_match("/title\"?\s?:\s?\"([^\"]+)\"/", $str, $matches);
			$jsstr = "{\"title\":\"{$matches[1]}\"}";
			$json = json_decode($jsstr, true);
			$data['title'] = $json['title'];
			// url
			$data['url'] = $url;
			// query
			preg_match("/\"(vid=[^\"]+)\"\sname=\"flashVars\"/s", $html, $matches);
			$query = str_replace("&amp;", '&', $matches[1]);
			preg_match("/\/\/player\.ku6cdn\.com[^\"\']+/", $html, $matches);
			$data['flv'] = 'http:'.$matches[0].'?'.$query;

			return $data;
		}
	}

	/**
	 * 56网
	 * http://www.56.com/u73/v_NTkzMDcwNDY.html
	 * http://player.56.com/v_NTkzMDcwNDY.swf
	 */
	private function _parse56($url){
		preg_match("#/v_(\w+)\.html#", $url, $matches);

		if (empty($matches)){
			preg_match("#/play_album-aid-(\d+)_vid-(\w+).html#", $url, $matches);
			if (empty($matches)) return false;
			$iid = $matches[2];
		}else{
			$iid = $matches[1];
		}

		$link="http://vxml.56.com/json/$iid}/?src=out";
		$retval = get_contents($link);

		if ($retval) {
			$json = json_decode($retval, true);

			$data['imgurl'] = $json['info']['img'];
			$data['title'] = $json['info']['Subject'];
			$data['url'] = $url;
			$data['flv'] = "http://player.56.com/v_{$iid}.swf";

			return $data;
		} else {
			return false;
		}
	}

	/**
	 * 乐视网
	 * http://www.letv.com/ptv/vplay/1168109.html
	 * http://www.letv.com/player/x1168109.swf
	 */
	private function _parseLetv($url){
		$html = get_contents($url);
		preg_match("#http://v.t.sina.com.cn/([^'\"]*)#", $html, $matches);
		parse_str(parse_url(urldecode($matches[0]), PHP_URL_QUERY));
		preg_match("#vplay/(\d+)#", $url, $matches);
		$data['imgurl'] = $pic;
		$data['title'] = $title;
		$data['url'] = $url;
		$data['flv'] = "http://www.letv.com/player/x{$matches[1]}.swf";

		return $data;
	}

	// 搜狐TV http://my.tv.sohu.com/u/vw/5101536
	private function _parseSohu($url){
		$html = get_contents($url);
		$html = iconv("GB2312", "UTF-8", $html);
		preg_match_all("/og:(?:title|image|videosrc)\"\scontent=\"([^\"]+)\"/s", $html, $matches);
		$data['imgurl'] = $matches[1][2];
		$data['title'] = $matches[1][1];
		$data['url'] = $url;
		$data['flv'] = $matches[1][0];
		return $data;
	}
	
	// Redtube http://www.redtube.com/536642
	private function _parseRedtube($url){
		$html = get_contents($url);
		preg_match("#com/(\d+)#", $url, $matchess);
		$vid = $matchess[1];

		//<meta property="og:image" content="http://img04.redtubefiles.com/_thumbs/0000047/0047652/0047652_011m.jpg" />
		preg_match("/og:image\"\scontent=\"([^\"]+)\"/s", $html, $matches);
		
		//description: "Doing the split for this hard cock"
		preg_match("/description:\s\"([^\"]+)\"/s", $html, $matchest);
		
		$data['imgurl'] = $matches[1];
		//$data['url'] = $url;
		$data['title'] = $matchest[1];
		$data['flv'] = "http://embed.redtube.com/player/?id={$vid}&style=redtube";
		return $data;
	}

	/*
	 * 新浪播客
	* http://video.sina.com.cn/v/b/48717043-1290055681.html
	* http://you.video.sina.com.cn/api/sinawebApi/outplayrefer.php/vid=48717043_1290055681_PUzkSndrDzXK+l1lHz2stqkP7KQNt6nki2O0u1ehIwZYQ0/XM5GdatoG5ynSA9kEqDhAQJA4dPkm0x4/s.swf
	*/
	private function _parseSina($url){
		preg_match("/(\d+)(?:\-|\_)(\d+)/", $url, $matches);
		$url = "http://video.sina.com.cn/v/b/{$matches[1]}-{$matches[2]}.html";
		$html = get_contents($url);
		preg_match("/video\s?:\s?([^<]+)}/", $html, $matches);
		$find = array("/\n/", "/\s*/", "/\'/", "/\{([^:,]+):/", "/,([^:]+):/", "/:[^\d\"]\w+[^\,]*,/i");
		$replace = array('', '', '"', '{"\\1":', ',"\\1":', ':"",');
		$str = preg_replace($find, $replace, $matches[1]);
		$arr = json_decode($str, true);

		$data['imgurl'] = $arr['pic'];
		$data['title'] = $arr['title'];
		$data['url'] = $url;
		$data['flv'] = $arr['swfOutsideUrl'];

		return $data;
	}
	
	private function _parseYoutube($url){
			//$flv = 'http://www.youtube.com/v/'.$matches[1].'&hl=zh_CN&fs=1';
			$str = file_get_contents($url, false, $ctx);
			if(!empty($str) && preg_match("/<meta property=\"og:video\" content=\"(.+?)\">/i", $str, $video)) {
				$flv = trim($video[1]);
			}
			if(!empty($str) && preg_match("/<meta property=\"og:title\" content=\"(.+?)\">/i", $str, $desc)) {
				$title = htmlspecialchars_decode(trim($desc[1]));
				
			}
			if(!empty($str) && preg_match("/<meta property=\"og:image\" content=\"(.+?)\">/i", $str, $image)) {
				$imgurl = trim($image[1]);
			}
		return array('flv' => $flv, 'imgurl' => $imgurl,'title'=>$title);
	}

	private function _parseiqi($url){
		$api = $url;
		$str = file_get_contents($api, false, $ctx);
		if(!empty($str) && preg_match("/\"?url\s*\"?:\s*\"(.+?)\"/i", $str, $qyurl)) {
			$qyurl = trim($qyurl[1]);
		}
		if(!empty($qyurl) && preg_match("/\/(\d+)\/(.+?).html/i", $qyurl, $qyurl_param)) {
			$date = trim($qyurl_param[1]);
			$code = trim($qyurl_param[2]);
			if(strpos($qyurl, 'yule')!=false){
				$type = 'yule';
			}
		}
		if(!empty($qyurl) && preg_match("/\/(\w+?)\/(\d+)\/(.+?).html/i", $qyurl, $qyurl_param)) {
			$type = trim($qyurl_param[1]);
		}
		if(!empty($str) && preg_match("/\"?title\s*\"?:\s*\"(.+?)\"/i", $str, $qytitle)) {
			$title = trim($qytitle[1]);
		}
		if(!empty($str) && preg_match("/\"?videoId\s*\"?:\s*\"(.+?)\"/i", $str, $qyvideoid)) {
			$qyvideoid = trim($qyvideoid[1]);
		}
		if(!empty($str) && preg_match("/\"?tvId\s*\"?:\s*\"(.+?)\"/i", $str, $tvid)) {
			$tvid = trim($tvid[1]);
		}
		if(!empty($str) && preg_match("/\"?pid\s*\"?:\s*\"(.+?)\"/i", $str, $pid)) {
			$pid = trim($pid[1]);
		}
		if(!empty($str) && preg_match("/\"?ptype\s*\"?:\s*\"(.+?)\"/i", $str, $ptype)) {
			$ptype = trim($ptype[1]);
		}
		if(!empty($str) && preg_match("/\"?albumId\s*\"?:\s*\"(.+?)\"/i", $str, $albumId)) {
			$albumId = trim($albumId[1]);
		}
		if(!empty($str) && preg_match("/\"?qitanId\s*\"?:\s*\"(.+?)\"/i", $str, $qitanId)) {
			$qitanId = trim($qitanId[1]);
		}
		if(!empty($str) && preg_match("/<span id=\"imgPathData\" style=\"display:none\">(.+?)<\/span>/i", $str, $image)) {
			$imgurl = trim(str_replace('_baidu', '', $image[1]));
		}
		if(!empty($date) && !empty($type) && !empty($code) && !empty($tvid)&& !empty($qyvideoid)){
			if($type=='dianying') $fl_type='6296';
			else if($type=='dianshiju') $fl_type='2736';
			else $fl_type='600';
			$flv = "http://player.video.qiyi.com/{$qyvideoid}/0/{$fl_type}/{$type}/{$date}/{$code}.swf-pid={$pid}-ptype={$ptype}-albumId={$albumId}-tvId={$tvid}-autoplay=0-qitanId={$qitanId}-isDrm=0-isPurchase=0";
		}
		
		return array('flv' => $flv, 'imgurl' => $imgurl,'title'=>$title);
	}
	
}
